const {User} = require('../models');
const md5 = require('md5')

module.exports = class {
  static async register (ctx) {
    //拿数据
    //md5
    //创建
    //发送报文
    const post = ctx.request.body;
    post.password = md5(post.password)
    let result;
    try{
      result = await User.create(post);

    }catch(error){
      return ctx.body = {success: false, error, message: '该账号已被注册！'}
    }
    ctx.body = {success: true, data: result, message: '注册成功'}
  }
  static async login (ctx) {
    const post = ctx.request.body;
    post.password = md5(post.password);
    let result;
    try {
      result = await User.findOne({
        where: {
          username: post.username,
        }
      })
    } catch (error) {
      return ctx.body = {success: false, error, message: '服务器有毒'}
    }
    const body = {data: result}
    if( result ) {
      const b = result.password == post.password;
      ctx.session = result;
      console.log(ctx.session);
      body.success = b;
      if(b) {
        ctx.session = result;
        body.message = '登录成功！'
      } else {
        body.message = '密码错误！'
      }
    } else {
      body.success = false;
      body.message = '没有该账号'
    }
    ctx.body = body;
  }
  static async details (ctx) {
    // console.log(ctx.session.dataValues);
    // ctx.body = ctx.session.dataValues;
    const { username } = ctx.request.body;
    const result = await User.findOne({
      where: {
        username
      }
    })
    ctx.body = { success: true, data: result, message: '成功'}
  }
  static verification (ctx) {
    console.log(ctx.session, ctx.session.dataValues);
    ctx.body = {success: !!ctx.session.dataValues}
  }
  static SignOut (ctx) {
    ctx.session = {};
    ctx.body = {success: true, message: '退出成功'}
  }
}